{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "\n",
    "# Import conventions we'll be using here. See Part 1\n",
    "import matplotlib\n",
    "matplotlib.use('nbagg')\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Limits, Legends, and Layouts\n",
    "\n",
    "In this section, we'll focus on what happens around the edges of the axes:  Ticks, ticklabels, limits, layouts, and legends."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Limits and autoscaling\n",
    "\n",
    "By default, Matplotlib will attempt to determine limits for you that encompasses all the data you have plotted.  This is the \"autoscale\" feature. For image plots, the limits are not padded while plots such as scatter plots and bar plots are given some padding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=plt.figaspect(0.5))\n",
    "\n",
    "ax1.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])\n",
    "ax2.scatter([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `ax.margins(...)`\n",
    "\n",
    "If you'd like to add a bit of \"padding\" to a plot, `ax.margins(<some_small_fraction>)` is a very handy way to do so.  Instead of choosing \"even-ish\" numbers as min/max ranges for each axis, `margins` will make Matplotlib calculate the min/max of each axis by taking the range of the data and adding on a fractional amount of padding.\n",
    "\n",
    "As an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=plt.figaspect(0.5))\n",
    "\n",
    "ax1.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])\n",
    "ax2.scatter([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])\n",
    "\n",
    "ax1.margins(x=0.0, y=0.1) # 10% padding in the y-direction only\n",
    "ax2.margins(0.05) # 5% padding in all directions\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `ax.axis(...)`\n",
    "\n",
    "The `ax.axis(...)` method is a convienent way of controlling the axes limits and enabling/disabling autoscaling.\n",
    "\n",
    "If you ever need to get all of the current plot limits, calling `ax.axis()` with no arguments will return the xmin/max/etc:\n",
    "\n",
    "    xmin, xmax, ymin, ymax = ax.axis()\n",
    "    \n",
    "If you'd like to manually set all of the x/y limits at once, you can use `ax.axis` for this, as well (note that we're calling it with a single argument that's a sequence, not 4 individual arguments):\n",
    "\n",
    "    ax.axis([xmin, xmax, ymin, ymax])\n",
    "    \n",
    "However, you'll probably use `axis` mostly with either the `\"tight\"` or `\"equal\"` options. There are other options as well; see the documentation for full details.  In a nutshell, though:\n",
    "\n",
    "  * *tight*: Set axes limits to the exact range of the data\n",
    "  * *equal*: Set axes scales such that one cm/inch in the y-direction is the same as one cm/inch in the x-direction. In Matplotlib terms, this sets the aspect ratio of the plot to 1.  That _doesn't_ mean that the axes \"box\" will be square.\n",
    "  \n",
    "And as an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(nrows=3)\n",
    "\n",
    "for ax in axes:\n",
    "    ax.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])\n",
    "\n",
    "axes[0].set_title('Normal Autoscaling', y=0.7, x=0.8)\n",
    "\n",
    "axes[1].set_title('ax.axis(\"tight\")', y=0.7, x=0.8)\n",
    "axes[1].axis('tight')\n",
    "\n",
    "axes[2].set_title('ax.axis(\"equal\")', y=0.7, x=0.8)\n",
    "axes[2].axis('equal')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Manually setting only one limit\n",
    "\n",
    "Another trick with limits is to specify only half of a limit. When done **after** a plot is made, this has the effect of allowing the user to anchor a limit while letting Matplotlib autoscale the rest of it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Good -- setting limits after plotting is done\n",
    "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=plt.figaspect(0.5))\n",
    "ax1.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])\n",
    "ax2.scatter([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])\n",
    "ax1.set_ylim(bottom=-10)\n",
    "ax2.set_xlim(right=25)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Bad -- Setting limits before plotting is done\n",
    "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=plt.figaspect(0.5))\n",
    "ax1.set_ylim(bottom=-10)\n",
    "ax2.set_xlim(right=25)\n",
    "ax1.plot([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])\n",
    "ax2.scatter([-10, -5, 0, 5, 10, 15], [-1.2, 2, 3.5, -0.3, -4, 1])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Legends\n",
    "\n",
    "As you've seen in some of the examples so far, the X and Y axis can also be labeled, as well as the subplot itself via the title. \n",
    "\n",
    "However, another thing you can label is the line/point/bar/etc that you plot.  You can provide a label to your plot, which allows your legend to automatically build itself. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot([1, 2, 3, 4], [10, 20, 25, 30], label='Philadelphia')\n",
    "ax.plot([1, 2, 3, 4], [30, 23, 13, 4], label='Boston')\n",
    "ax.set(ylabel='Temperature (deg C)', xlabel='Time', title='A tale of two cities')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In `classic` mode, legends will go in the upper right corner by default (you can control this with the `loc` kwarg). As of v2.0, by default Matplotlib will choose a location to avoid overlapping plot elements as much as possible. To force this option, you can pass in:\n",
    "\n",
    "    ax.legend(loc=\"best\")\n",
    "    \n",
    "Also, if you happen to be plotting something that you do not want to appear in the legend, just set the label to \"\\_nolegend\\_\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(1, 1)\n",
    "ax.bar([1, 2, 3, 4], [10, 20, 25, 30], label=\"Foobar\", align='center', color='lightblue')\n",
    "ax.plot([1, 2, 3, 4], [10, 20, 25, 30], label=\"_nolegend_\", marker='o', color='darkred')\n",
    "ax.legend(loc='best')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exercise 4.1\n",
    "\n",
    "Once again, let's use a bit of what we've learned.  Try to reproduce the following figure:\n",
    "\n",
    "<img src=\"images/exercise_4-1.png\">\n",
    "\n",
    "Hint: You'll need to combine `ax.axis(...)` and `ax.margins(...)`.  Here's the data and some code to get you started:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%load exercises/4.1-legends_and_scaling.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.style.use('classic')\n",
    "\n",
    "t = np.linspace(0, 2 * np.pi, 150)\n",
    "x1, y1 = np.cos(t), np.sin(t)\n",
    "x2, y2 = 2 * x1, 2 * y1\n",
    "\n",
    "colors = ['darkred', 'darkgreen']\n",
    "\n",
    "# Try to plot the two circles, scale the axes as shown and add a legend\n",
    "# Hint: it's easiest to combine `ax.axis(...)` and `ax.margins(...)` to scale the axes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dealing with the boundaries: Layout, ticks, spines, etc\n",
    "\n",
    "One key thing we haven't talked about yet is all of the annotation on the outside of the axes, the borders of the axes, and how to adjust the amount of space around the axes.  We won't go over every detail, but this next section should give you a reasonable working knowledge of how to configure what happens around the edges of your axes.\n",
    "\n",
    "## Ticks, Tick Lines, Tick Labels and Tickers\n",
    "This is a constant source of confusion:\n",
    "\n",
    "* A Tick is the *location* of a Tick Label.\n",
    "* A Tick Line is the line that denotes the location of the tick.\n",
    "* A Tick Label is the text that is displayed at that tick.\n",
    "* A [`Ticker`](http://matplotlib.org/api/ticker_api.html#module-matplotlib.ticker) automatically determines the ticks for an Axis and formats the tick labels.\n",
    "\n",
    "[`tick_params()`](https://matplotlib.org/api/axes_api.html#ticks-and-tick-labels) is often used to help configure your tickers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot([1, 2, 3, 4], [10, 20, 25, 30])\n",
    "\n",
    "# Manually set ticks and tick labels *on the x-axis* (note ax.xaxis.set, not ax.set!)\n",
    "ax.xaxis.set(ticks=range(1, 5), ticklabels=[3, 100, -12, \"foo\"]) \n",
    "\n",
    "# Make the y-ticks a bit longer and go both in and out...\n",
    "ax.tick_params(axis='y', direction='inout', length=10)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A commonly-asked question is \"How do I plot categories?\"\n",
    "\n",
    "Starting in version 2.0 of mpl, just like any other data.\n",
    "\n",
    "For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "data = [('apples', 2), ('oranges', 3), ('peaches', 1)]\n",
    "fruit, value = zip(*data)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.bar(fruit, value, align='center', color='gray')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Subplot Spacing\n",
    "The spacing between the subplots can be adjusted using [`fig.subplots_adjust()`](http://matplotlib.org/api/pyplot_api.html?#matplotlib.pyplot.subplots_adjust). Play around with the example below to see how the different arguments affect the spacing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(2, 2, figsize=(9, 9))\n",
    "fig.subplots_adjust(wspace=0.5, hspace=0.3,\n",
    "                    left=0.125, right=0.9,\n",
    "                    top=0.9,    bottom=0.1)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A common \"gotcha\" is that the labels are not automatically adjusted to avoid overlapping those of another subplot. Matplotlib does not currently have any sort of robust layout engine, as it is a design decision to minimize the amount of \"magical plotting\". We intend to let users have complete, 100% control over their plots. LaTeX users would be quite familiar with the amount of frustration that can occur with automatic placement of figures in their documents.\n",
    "\n",
    "That said, there have been some efforts to develop tools that users can use to help address the most common compaints. The \"[Tight Layout](http://matplotlib.org/users/tight_layout_guide.html)\" feature, when invoked, will attempt to resize margins and subplots so that nothing overlaps.\n",
    "\n",
    "If you have multiple subplots, and want to avoid overlapping titles/axis labels/etc, `fig.tight_layout` is a great way to do so:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def example_plot(ax):\n",
    "    ax.plot([1, 2])\n",
    "    ax.set_xlabel('x-label', fontsize=16)\n",
    "    ax.set_ylabel('y-label', fontsize=8)\n",
    "    ax.set_title('Title', fontsize=24)\n",
    "\n",
    "fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)\n",
    "example_plot(ax1)\n",
    "example_plot(ax2)\n",
    "example_plot(ax3)\n",
    "example_plot(ax4)\n",
    "\n",
    "# Enable fig.tight_layout to compare...\n",
    "#fig.tight_layout()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## GridSpec\n",
    "Under the hood, Matplotlib utilizes [`GridSpec`](http://matplotlib.org/api/gridspec_api.html) to lay out the subplots. While `plt.subplots()` is fine for simple cases, sometimes you will need more advanced subplot layouts. In such cases, you should use GridSpec directly. GridSpec is outside the scope of this tutorial, but it is handy to know that it exists. [Here](http://matplotlib.org/users/gridspec.html) is a guide on how to use it."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sharing axes\n",
    "There will be times when you want to have the x axis and/or the y axis of your subplots to be \"shared\". Sharing an axis means that the axis in one or more subplots will be tied together such that any change in one of the axis changes all of the other shared axes. This works very nicely with autoscaling arbitrary datasets that may have overlapping domains. Furthermore, when interacting with the plots (panning and zooming), all of the shared axes will pan and zoom automatically."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)\n",
    "ax1.plot([1, 2, 3, 4], [1, 2, 3, 4])\n",
    "ax2.plot([3, 4, 5, 6], [6, 5, 4, 3])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## \"Twinning\" axes\n",
    "Sometimes one may want to overlay two plots on the same axes, but the scales may be entirely different. You can simply treat them as separate plots, but then twin them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, ax1 = plt.subplots(1, 1)\n",
    "ax1.plot([1, 2, 3, 4], [1, 2, 3, 4])\n",
    "ax2 = ax1.twinx()\n",
    "ax2.scatter([1, 2, 3, 4], [60, 50, 40, 30])\n",
    "ax1.set(xlabel='X', ylabel='First scale')\n",
    "ax2.set(ylabel='Other scale')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Axis Spines\n",
    "Spines are the axis lines for a plot. Each plot can have four spines: \"top\", \"bottom\", \"left\" and \"right\". By default, they are set so that they frame the plot, but they can be individually positioned and configured via the [`set_position()`](http://matplotlib.org/api/spines_api.html#matplotlib.spines.Spine.set_position) method of the spine. Here are some different configurations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot([-2, 2, 3, 4], [-10, 20, 25, 5])\n",
    "ax.spines['top'].set_visible(False)\n",
    "ax.xaxis.set_ticks_position('bottom')  # no ticklines at the top\n",
    "ax.spines['right'].set_visible(False)\n",
    "ax.yaxis.set_ticks_position('left')  # no ticklines on the right\n",
    "\n",
    "# \"outward\"\n",
    "# Move the two remaining spines \"out\" away from the plot by 10 points\n",
    "#ax.spines['bottom'].set_position(('outward', 10))\n",
    "#ax.spines['left'].set_position(('outward', 10))\n",
    "\n",
    "# \"data\"\n",
    "# Have the spines stay intersected at (0,0)\n",
    "#ax.spines['bottom'].set_position(('data', 0))\n",
    "#ax.spines['left'].set_position(('data', 0))\n",
    "\n",
    "# \"axes\"\n",
    "# Have the two remaining spines placed at a fraction of the axes\n",
    "#ax.spines['bottom'].set_position(('axes', 0.75))\n",
    "#ax.spines['left'].set_position(('axes', 0.3))\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exercise 4.2\n",
    "\n",
    "This one is a bit trickier.  Once again, try to reproduce the figure below:\n",
    "\n",
    "<img src=\"images/exercise_4-2.png\">\n",
    "\n",
    "\n",
    "A few key hints: The two subplots have no vertical space between them (this means that the `hspace` is `0`). Note that the bottom spine is at 0 in data coordinates and the tick lines are missing from the right and top sides.\n",
    "\n",
    "Because you're going to be doing a lot of the same things to both subplots, to avoid repitive code you might consider writing a function that takes an `Axes` object and makes the spine changes, etc to it. \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%load exercises/4.2-spines_ticks_and_subplot_spacing.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "# Try to reproduce the figure shown in images/exercise_4.2.png\n",
    "# This one is a bit trickier!\n",
    "\n",
    "# Here's the data...\n",
    "data = [('dogs', 4, 4), ('frogs', -3, 1), ('cats', 1, 5), ('goldfish', -2, 2)]\n",
    "animals, friendliness, popularity = zip(*data)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
